package com.lft.examsys.service;

import com.lft.examsys.entity.Kaptcha;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * @author ：Qingchen
 * @date ：Created in 2022/3/24 19:22
 * @description：生成验证码
 * @modified By：
 * @version: $
 */
@Service
public class KaptchaService {
    private static final int CodeCount = 10;

    private int width = 80;
    private int height = 20;
    private int fontHeight = 16;
    private int codeCount = 4;
    private final char[] codeSequence = new char[CodeCount];
    private int x = 16;
    private int codeY = 18;

    public Kaptcha generate() {

        for (int i = 0; i < 10; i++) {
            codeSequence[i] = (char) (i + 48);
        }
//        for (int i = 0; i < 26; i++) {
//            codeSequence[i + 10] = (char) ('A' + i);
//        }

        //构造预自定义图像
        BufferedImage Img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        //返回 Graphics2D
        Graphics g = Img.getGraphics();
        Random random = new Random();

        //填充图像为白色
        g.setColor(Color.WHITE);
        //填充指定的矩形
        g.fillRect(0, 0, width, height);
        //创建字体
        Font font = new Font("Times new Roman", Font.PLAIN, fontHeight);

        g.setColor(Color.black);
        g.setFont(font);
        Color juneFont = new Color(153, 204, 102);
        //随机产生130条干扰线
        g.setColor(juneFont);
        for (int j = 0; j < 200; j++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int x1 = random.nextInt(16);
            int y1 = random.nextInt(16);

            g.drawLine(x, y, x + x1, y + y1);
        }
        //randomCode保存随机产生的验证码
        StringBuffer randomCode = new StringBuffer();
        //随机产生codeCount数字验证码
        for (int i = 0; i < codeCount; i++) {
            String strRand = String.valueOf(codeSequence[random.nextInt(CodeCount)]);

            //用随机产生的颜色将验证码绘制到图像中
            g.setColor(new Color(20 + random.nextInt(110), 20 + random
                    .nextInt(110), 20 + random.nextInt(110)));

            //使用此图形上下文的当前文字和颜色绘制由指定string给定的文本
            g.drawString(strRand, (i + 1) * x - 4, codeY);
            randomCode.append(strRand);
        }
        return new Kaptcha(randomCode,Img);
    }
}
